const express=require('express');
const router=express.Router();
const PageJson=require("../model/PageJson");
const Stu_infoService=require("../services/Stu_infoService");
const path=require('path');
const fs=require('fs');
// const multer=require('multer');
// var upload=multer({
//   dest:path.join(__dirname,"../fileUpload")
// });
const upload=require('../utils/MulterUtil');

//登陆
router.get("/login/:s_id/:s_pwd",async (req,resp)=>{
  var stu_infoService=new Stu_infoService();
  try {
    var result=await stu_infoService.checkLogin(req.params.s_id,req.params.s_pwd);
    if(result.length==1){
      resp.json(new PageJson("success","登陆成功",result[0]));
    }
    else{
      resp.json(new PageJson("error","用户名与密码错误，请重试"));
    }
  } catch (error) {
    resp.json(new PageJson("error","服务器错误"));
  }
});


//获取我的信息
router.get("/getMyInfo/:s_id",async (req,resp)=>{
  var stu_infoService=new Stu_infoService();
  try {
    var result=await stu_infoService.getMyInfo(req.params.s_id);
    if(result.length==1){
      resp.json(new PageJson("success","获取信息成功",result[0]));
    }
    else{
      resp.json(new PageJson("error","获取信息失败"));
    }
  } catch (error) {
    resp.json(new PageJson("error","服务器错误"));
  }
});

router.post("/uploadPhoto",upload.single("s_photo"),async (req,resp)=>{
  var file=req.file;
  try {
    //相对路径
    var relativePath="/fileUpload/"+file.filename;
    var stu_infoService=new Stu_infoService();
    //保存到数据库
    var flag=await stu_infoService.uploadPhoto(req.body.s_id,relativePath);
    if(flag){
      var pageJson=new PageJson("success","上传成功",relativePath);
      resp.json(pageJson)
    }
    else{
      resp.json(new PageJson("error","图片上传失败"));
    }
    ;
  } catch (error) {
    console.log(error);
    resp.json(new PageJson("error","图片上传失败"));
  }
});

//获取用户图片
router.get("/findPhotoByS_id/:s_id",async (req,resp)=>{
  var s_id=req.params.s_id;
  var stu_infoService=new Stu_infoService();
  try {
    var path = await stu_infoService.findPhotoByS_id(s_id);
    if(path==null){
      resp.json(new PageJson("error","当前用户无图片"));
    }
    else{
      resp.json(new PageJson("success","获取成功，请具体判断是否该用户有图片",path));
    }
  } catch (error) {
    resp.json(new PageJson("error","获取失败，服务器错误"));
  }
});


router.get("/getStuListByC_id/:c_id",async (req,resp)=>{
  var stu_infoService=new Stu_infoService();
  try {
    var result = await stu_infoService.getStuListByC_id(req.params.c_id);
    resp.json(new PageJson("success","获取成功",result));
  } catch (error) {
    resp.json(new PageJson("error","获取失败，服务器错误"));
  }
});


module.exports=router;
